<%@ page import="com.macrosolution.exdebito.FileDocument" %>
<%@ page import="com.macrosolution.exdebito.Pratica" %>
<%@ page import="com.macrosolution.exdebito.AnomaliaBancaria" %>
<%@ page import="com.macrosolution.exdebito.Interview" %>
<%@ page import="com.macrosolution.exdebito.Perito" %>
<!DOCTYPE html>
<html>

<head>
	<meta name="layout" content="kickstart" />	
	<title><g:message code="Upload Documenti" /></title>
	
	<script type="text/javascript">
	
	$(document).ready(function(){
		load_folder();
		var  progress = $('myprogress').progressbar();
	});

	
	function add_p(){
		var ps = $('#peritoSelected').val();
		var pid = "${praticaInstance.id}";
		${remoteFunction(
			action:'savePerito',
			controller:'anomaliaBancaria',
			params: '\'id=\'+pid+\'&perito_id=\'+ps',
			onSuccess:'showAddP(data)'
		)}
	}
	
	
	function load_folder(){		
		${remoteFunction(
				action:'load_folder',
				type:'POST',
				params: [praticaId:praticaInstance.id],
				update: [success: 'folderList', failure: 'get'],
				onSuccess:'spinPage(false)',
				onLoading:'spinPage(true);',
				onFailure:'failureLoadPage(XMLHttpRequest,textStatus,errorThrown)',
				onComplete:'spinPage(false)'								
		)}
	}
		
	function showfDetails(fileId){
		${remoteFunction(
			action:'showFileDetail',
			type:'POST',
			update: [success: 'file_d', failure: 'get'],
		  	params: '\'fileId=\' + fileId',
			onSuccess:'spin(fileId,false);$("#fd_modal").modal()',
			onLoading:'spin(fileId,true);',
			onFailure:'showCancelResponse(XMLHttpRequest,textStatus,errorThrown)',
			onComplete:'spin(fileId,false)'
		)}
	}


	function showAddP(data){
		$.smallBox({
			title : data.message,
			color : "#3F8DBF",
			sound:false,
			timeout: 3000
		});
		setTimeout(function(){ location.reload();}, 2000);
		
	}
		
	function spin(fileId,onoff){
		if(onoff){
			$('#spin_'+fileId).fadeIn();
		}else{
			$('#spin_'+fileId).fadeOut();
		}	
	}
	
	function spinPage(onoff){
		if(onoff){
			$('#spinPage').fadeIn();	
		}else{
			$('#spinPage').fadeOut();
		}	
	}
	
	function showCancelResponse(a,b,c){		
		$.smallBox({
			title : a.responseText,
			color : "#3F8DBF",
			sound:false,
			timeout: 3000
		});		
	}
	
	function load_file(){		
		var praticaId = "${praticaInstance.id}";
		${remoteFunction(
				action:'load_file',
				type:'POST',
				update: [success: 'fileList', failure: 'get'],
				params:'\'praticaId=\'+praticaId',
				onSuccess:'spinPage(false)',
				onLoading:'spinPage(true);',
				onFailure:'failureLoadPage(XMLHttpRequest,textStatus,errorThrown)',
				onComplete:'spinPage(false)'								
			)}
	}
	
	function failureLoadPage(a,b,c){
		$.smallBox({
			title : a.responseText,
			color : "#3F8DBF",
			sound:true,
			timeout: 3000
		});
	}
	
	function fileCancelAlert(idFile,idPratica,folderId){		
		$.SmartMessageBox({
			title : "<div class='row'><div class='col-md-2'><i class='fa '></i></div><div class='col-md-10'>Sei Sicuro di voler eliminare questo file?</div>",
			content : "<div class='col-md-2'></div><div class='col-md-10'> <BR/><BR/></div></div>",
			buttons:"[Si],[No]",
			sound:false
		}, function(ButtonPressed, Value) {
			if (ButtonPressed === "No") {				
			}
			if (ButtonPressed === "Si") {
				${remoteFunction(asynchronous: true,
	 					action:'deleteAnomaliaFile',
						params:'\'id=\' + idFile + \'&id_pratica=\' + idPratica',
						update:[success:'filesList',failure:'filesList'],
						onFailure:'failureLoadPage(XMLHttpRequest,textStatus,errorThrown)',
						onLoading:'spinPage(true);',
						onComplete:'spinPage(false);show_files(folderId);load_folder()',
						onSuccess:'load_file()'						
				)} 
			}
		});
	}
	
	function show_files(folderId,orderby){
		var pId = "${praticaInstance.id}";
		${remoteFunction(asynchronous: true,
				action:'showFilesAnomalia',
				params:'\'folderId=\' + folderId + \'&pId=\' + pId+ \'&order_by=\' + orderby',
				update:[success:'filesList',failure:'filesList'],
				onFailure:'failureLoadPage(XMLHttpRequest,textStatus,errorThrown)',
				onLoading:'spinPage(true);',
				onComplete:'spinPage(false);'				
		)}
	}

	function uploadAj(){

		var piddi = $('#piddi').val()
		var folder = $('#documentType').val();
		var comments = $('#comments').val();
		var data = new FormData();
		data.append("documentType", folder);
		data.append("comments", comments);
		data.append("piddi",piddi);
		data.append("file", fileAnomal.files[0]);

		spinPage(true);
		pleaseWait();
		$.ajax({
			xhr: function()
			  {
			    var xhr = new window.XMLHttpRequest();
			    //Upload progress
			    xhr.upload.addEventListener("progress", function(evt){
			      if (evt.lengthComputable) {
				      
			        var percentComplete = evt.loaded / evt.total;
			        //Do something with upload progress
			        var cento = percentComplete*100;
<%--			        $('#myprogress').css('width', percentComplete+'%').attr('aria-valuenow', percentComplete);--%>
			        $('#myprogress').attr('aria-valuenow', cento);
			        $('#myprogress').css('width', cento + '%');

						$("#myprogress").html(cento.toFixed(0)+"%");
				   }
			    }, false);
			    //Download progress
			    xhr.addEventListener("progress", function(evt){
			      if (evt.lengthComputable) {
			        var percentComplete = evt.loaded / evt.total;
			        //Do something with download progress
			        $('.progress-bar').css('width', percentComplete+'%').attr('aria-valuenow', percentComplete);
					$("myprogress").html(percentComplete);
				   }
			    }, false);
			    return xhr;},
			
			url: "${createLink(action:'uploadAj')}",
		    type: 'POST',
		    data: data,
		    cache: false,
		     
		    processData: false, // Don't process the files
		    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
		    success: function(data, textStatus, jqXHR)
		    {
		       if(typeof data.error === 'undefined')
		        {
		                // Success so call function to process the form
		                successUpload(data,folder);
		                loadFileNumbers();
		                resetafterUp();
		                
		            }
		            else
		            {
		                // Handle errors here
		                
		                console.log('ERRORS: ' + data.error);
		            }
		        },
		        error: function(jqXHR, textStatus, errorThrown)
		        {
		            // Handle errors here
		            console.log('ERRORS: ' + textStatus);
		            
		            failureUpload(jqXHR,textStatus,errorThrown)
		            spinPage(false);
		            resetafterUp()
		            // STOP LOADING SPINNER
		        },
		        complete: function()
		        {
					spinPage(false);
					resetafterUp()
		            // STOP LOADING SPINNER
		        }
		    });
	

	}

		function pleaseWait(){
			$("#btnUpload").button('loading');
			$('#progressBox').fadeIn();
			$('#upCloseBtn').prop('disabled', true);
			$('#fileAnomal').prop('disabled',true);
			$('#documentType').prop('disabled',true);
			$('#comments').prop('disabled',true);
		
		}
		function resetafterUp(){
			$('#progressBox').hide();
			$("#btnUpload").button('reset');
			$('#upCloseBtn').prop('disabled', false);
			$('#myprogress').attr('aria-valuenow', 0);
	        $('#myprogress').css('width', 0 + '%');
	        $('#fileAnomal').prop('disabled',false);
	        $('#documentType').prop('disabled',false);
			$('#comments').prop('disabled',false);
		}
		
	function successUpload(data,folder){

		$.smallBox({
			title : data,
			color : "#3F8DBF",
			sound:false,
			timeout: 3000
		});
		show_files(folder);
		
	}
	function failureUpload(a,b,c){
		
		$.smallBox({
			title : a.responseText,
			color : "#a90329",
			sound:false,
			timeout: 3000
		});

	}
		
	function showAddPerito(data){
		$.smallBox({
			title : data.message,
			color : "#3F8DBF",
			sound:false,
			timeout: 3000
		});
		setTimeout(function(){ location.reload();}, 2000);			
	}	


	</script>
</head>


<body>	
	<div id="ribbon">
		<span class="ribbon-button-alignment"> 
			
		</span>
			<!-- breadcrumb -->
			<ol class="breadcrumb">
				<li>Home</li><li>Pratiche</li><li>Rapporto Bancario</li><li>Caricamento File</li>
			</ol>
			<!-- end breadcrumb -->
	</div>

	<div id="content">	
		<div class="row">		
			<div class="col-xs-12 col-sm-10 col-md-10 col-lg-10">
				<h4 class="page-title txt-color-blueDark"><i class="fa fa-desktop fa-fw "></i> 
					Gestione Pratiche
					<span class="txt-color-blue">>
						${praticaInstance?.identifier}						
					</span>
					<span>>
						Rapporto Bancario
					</span>
				</h4>
			</div>
			<div class="row" style="margin-top:8px">
				<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2">
					<a type="button" name="int" class="btn btn-primary"	
						href="${createLink(controller:'interview',
									action:'edit',
									id:(Pratica.findByIdentifier(praticaInstance?.identifier)).anomaliaBancaria.interviewId
							)}">
						 Torna in Intervista</a>
				</div>
			</div>
			<sec:ifAnyGranted roles="ROLE_ADMIN,ROLE_AMM,ROLE_BCKOFF">
		<div class="row">		
			<div class="col-xs-5 col-sm-5 col-md-5 col-lg-5">
				<div class="form-group">
					<div class="input-group" id="input-group-perito">
						&nbsp;&nbsp;<span class="input-group-addon"><i class="fa  fa-graduation-cap fa-lg fa-fw"></i></span>
				<g:select class="form-control" id="peritoSelected" name="value" from="${com.macrosolution.exdebito.Perito?.list()}" 
					value="${(Pratica.findByIdentifier(praticaInstance?.identifier)).anomaliaBancaria?.perito?.id}" 
					optionKey="id" optionValue="surname" noSelection="['-1':'- Seleziona il Perito da associare alla Pratica -']"/>
					</div>
				</div>
			</div>
			<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2">
				<input type="button" class="btn btn-info btn-sm col-md-offset-2" name="add_perito" id="add_perito" value="&nbsp;&nbsp;Salva Perito&nbsp;&nbsp;" 
					onClick="add_p()" class="fa fa-plus-circle">
			</div>
		</div>	
		</sec:ifAnyGranted>		
		</div>

		<g:hasErrors bean="${praticaInstance}">
			<div class="alert alert-danger">
				<g:renderErrors bean="${praticaInstance}" as="list" />
			</div>
		</g:hasErrors>
		<g:if test="${flash.message }">
			<div class="row">
				<div class="col col-md-6">				
					<div class="alert alert-warning fade in">
						<button class="close" data-dismiss="alert">
							×
						</button>
						<i class="fa-fw fa fa-check"></i>
						<strong><g:message code="${flash.message}"/></strong> 
					</div>		
				</div>	
			</div>
		</g:if>
		
	<div class="row">
		<article class="col-sm-12 sortable-grid ui-sortable">

			<!-- Widget ID (each widget will need unique ID)-->		
			<!-- end widget -->

		<div class="jarviswidget well jarviswidget" id="wid-id-0" role="widget" style="">
			
			<header role="heading"><div class="jarviswidget-ctrls" role="menu">  <a href="javascript:void(0);" class="button-icon jarviswidget-edit-btn" rel="tooltip" title="" data-placement="bottom" data-original-title="Edit Title"><i class="fa fa-cog "></i></a> <a href="javascript:void(0);" class="button-icon jarviswidget-toggle-btn" rel="tooltip" title="" data-placement="bottom" data-original-title="Collapse"><i class="fa fa-minus "></i></a> <a href="javascript:void(0);" class="button-icon jarviswidget-fullscreen-btn" rel="tooltip" title="" data-placement="bottom" data-original-title="Fullscreen"><i class="fa fa-expand "></i></a> <a href="javascript:void(0);" class="button-icon jarviswidget-delete-btn" rel="tooltip" title="" data-placement="bottom" data-original-title="Delete"><i class="fa fa-times"></i></a></div><div class="widget-toolbar" role="menu"><a data-toggle="dropdown" class="dropdown-toggle color-box selector" href="javascript:void(0);"></a><ul class="dropdown-menu arrow-box-up-right color-select pull-right"><li><span class="bg-color-green" data-widget-setstyle="jarviswidget-color-green" rel="tooltip" data-placement="left" data-original-title="Green Grass"></span></li><li><span class="bg-color-greenDark" data-widget-setstyle="jarviswidget-color-greenDark" rel="tooltip" data-placement="top" data-original-title="Dark Green"></span></li><li><span class="bg-color-greenLight" data-widget-setstyle="jarviswidget-color-greenLight" rel="tooltip" data-placement="top" data-original-title="Light Green"></span></li><li><span class="bg-color-purple" data-widget-setstyle="jarviswidget-color-purple" rel="tooltip" data-placement="top" data-original-title="Purple"></span></li><li><span class="bg-color-magenta" data-widget-setstyle="jarviswidget-color-magenta" rel="tooltip" data-placement="top" data-original-title="Magenta"></span></li><li><span class="bg-color-pink" data-widget-setstyle="jarviswidget-color-pink" rel="tooltip" data-placement="right" data-original-title="Pink"></span></li><li><span class="bg-color-pinkDark" data-widget-setstyle="jarviswidget-color-pinkDark" rel="tooltip" data-placement="left" data-original-title="Fade Pink"></span></li><li><span class="bg-color-blueLight" data-widget-setstyle="jarviswidget-color-blueLight" rel="tooltip" data-placement="top" data-original-title="Light Blue"></span></li><li><span class="bg-color-teal" data-widget-setstyle="jarviswidget-color-teal" rel="tooltip" data-placement="top" data-original-title="Teal"></span></li><li><span class="bg-color-blue" data-widget-setstyle="jarviswidget-color-blue" rel="tooltip" data-placement="top" data-original-title="Ocean Blue"></span></li><li><span class="bg-color-blueDark" data-widget-setstyle="jarviswidget-color-blueDark" rel="tooltip" data-placement="top" data-original-title="Night Sky"></span></li><li><span class="bg-color-darken" data-widget-setstyle="jarviswidget-color-darken" rel="tooltip" data-placement="right" data-original-title="Night"></span></li><li><span class="bg-color-yellow" data-widget-setstyle="jarviswidget-color-yellow" rel="tooltip" data-placement="left" data-original-title="Day Light"></span></li><li><span class="bg-color-orange" data-widget-setstyle="jarviswidget-color-orange" rel="tooltip" data-placement="bottom" data-original-title="Orange"></span></li><li><span class="bg-color-orangeDark" data-widget-setstyle="jarviswidget-color-orangeDark" rel="tooltip" data-placement="bottom" data-original-title="Dark Orange"></span></li><li><span class="bg-color-red" data-widget-setstyle="jarviswidget-color-red" rel="tooltip" data-placement="bottom" data-original-title="Red Rose"></span></li><li><span class="bg-color-redLight" data-widget-setstyle="jarviswidget-color-redLight" rel="tooltip" data-placement="bottom" data-original-title="Light Red"></span></li><li><span class="bg-color-white" data-widget-setstyle="jarviswidget-color-white" rel="tooltip" data-placement="right" data-original-title="Purity"></span></li><li><a href="javascript:void(0);" class="jarviswidget-remove-colors" data-widget-setstyle="" rel="tooltip" data-placement="bottom" data-original-title="Reset widget color to default">Remove</a></li></ul></div>
				<span class="widget-icon"> <i class="fa fa-comments"></i> </span>
				<h2>My Data </h2>

				<span class="jarviswidget-loader"><i id="spin_test" class="fa fa-refresh fa-spin"></i></span></header>

				<!-- widget div-->
				<div role="content">				
					<!-- widget edit box -->
					<div class="jarviswidget-editbox">
						<!-- This area used as dropdown edit box -->
					</div>
					<!-- end widget edit box -->
					<!-- widget content -->
					<div class="widget-body">
						
						<div class="row">
							
							<div class="col-xs-12 col-sm-6 col-md-10 col-lg-5 " >
								<sec:ifNotGranted roles="ROLE_AVV">	
								
								<button type="button" class="btn btn-default" data-toggle="modal" data-target="#fileUpload_modal">
									Aggiungi un file
								</button>
								
								</sec:ifNotGranted>
								
								<div id="folderList">
									<%--FOLDER THREE	--%>							
								</div>
								
								
								
							
							</div>
							<div class="col-xs-12 col-sm-1 col-md-1 col-lg-1 " >
							
								<i id="spinPage" class="fa fa-gear fa-2x fa-spin"></i>
								
							</div>
							<div id="filesList" class="col-xs-12 col-sm-6 col-md-10 col-lg-6 " >
							
							
							
							</div>					
						
						</div>
					
					</div>
					<!-- end widget content -->
			</div>
			<!-- end widget div -->
		</div></article>
	</div>		
</div>

<div id="file_d">
	<g:render template="filedetailpopup"></g:render>
</div>
<g:render template="formUpload" model="[praticaInstance:praticaInstance]"></g:render>
</body>

</html>